##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

from PyQt4 import QtCore, QtGui

from lisp.core import actions
from lisp.utils import configuration
from lisp.ui import about
from lisp.ui.preferences import preferences
from lisp.ui.preferences.application import general


class MainWindow(QtGui.QMainWindow):

    PREFERENCES_WIDGETS = [general.General]

    newProgramAction = QtCore.pyqtSignal()
    saveProgramAction = QtCore.pyqtSignal(str)
    openProgramAction = QtCore.pyqtSignal(str)
    addMediaAction = QtCore.pyqtSignal(list)
    multiEditAction = QtCore.pyqtSignal()
    selectAllAction = QtCore.pyqtSignal()
    deselectAllAction = QtCore.pyqtSignal()
    invertSelectionAction = QtCore.pyqtSignal()

    def __init__(self):
        super(MainWindow, self).__init__()

        self.setMinimumSize(400, 300)

        # Define the collectorUi and the main gui's elements
        self.centralwidget = QtGui.QWidget(self)
        self.setCentralWidget(self.centralwidget)
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.setContentsMargins(0, 5, 0, 0)
        self.collectorUi = None

        # Status Bar
        self.statusBar = QtGui.QStatusBar(self)
        self.setStatusBar(self.statusBar)
        actions.actionHandler.infoSignal.connect(self.statusBar.showMessage)

        # Menubar
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 0, 25))
        self.menubar.setContextMenuPolicy(QtCore.Qt.PreventContextMenu)

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuEdit = QtGui.QMenu(self.menubar)
        self.menuLayout = QtGui.QMenu(self.menubar)
        self.menuTools = QtGui.QMenu(self.menubar)
        self.menuAbout = QtGui.QMenu(self.menubar)

        self.menubar.addMenu(self.menuFile)
        self.menubar.addMenu(self.menuEdit)
        self.menubar.addMenu(self.menuLayout)
        self.menubar.addMenu(self.menuTools)
        self.menubar.addMenu(self.menuAbout)

        self.setMenuBar(self.menubar)

        # menuFile
        self.actionNew_Programma = QtGui.QAction(self, triggered=self.newProgram)
        self.actionOpen = QtGui.QAction(self, triggered=self.openProgram)
        self.actionSave = QtGui.QAction(self, triggered=self.save)
        self.actionSave_with_name = QtGui.QAction(self, triggered=self.saveWithName)
        self.actionPreferences = QtGui.QAction(self, triggered=self.showPreferences)
        self.actionExit = QtGui.QAction(self, triggered=self.exit)

        self.menuFile.addAction(self.actionNew_Programma)
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSave_with_name)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionPreferences)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)

        # menuEdit
        self.actionNewMedia = QtGui.QAction(self, triggered=self.addMedia)
        self.actionUndo = QtGui.QAction(self, triggered=actions.actionHandler.undo)
        self.actionRedo = QtGui.QAction(self, triggered=actions.actionHandler.redo)
        self.actionMultiEdit = QtGui.QAction(self, triggered=self.multiEdit)
        self.actionSelectAll = QtGui.QAction(self, triggered=self.selectAll)
        self.actionDeselectAll = QtGui.QAction(self, triggered=self.deselectAll)
        self.actionInvertSelection = QtGui.QAction(self, triggered=self.invertSelection)

        self.menuEdit.addAction(self.actionNewMedia)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionUndo)
        self.menuEdit.addAction(self.actionRedo)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionSelectAll)
        self.menuEdit.addAction(self.actionDeselectAll)
        self.menuEdit.addAction(self.actionInvertSelection)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionMultiEdit)

        # menuAbout
        self.actionAbout = QtGui.QAction(self, triggered=lambda: about.About(self).show())
        self.actionAbout_Qt = QtGui.QAction(self, triggered=QtGui.qApp.aboutQt)

        self.menuAbout.addSeparator()
        self.menuAbout.addAction(self.actionAbout)
        self.menuAbout.addAction(self.actionAbout_Qt)

        # Set component text
        self.retranslateUi()
        # The save file name
        self.file = ''

        # Show the window maximized
        self.showMaximized()

    def retranslateUi(self):
        self.setWindowTitle('Linux Show Player')
        # menuFile
        self.menuFile.setTitle("&File")
        self.actionNew_Programma.setText("New")
        self.actionNew_Programma.setShortcut("CTRL+N")
        self.actionOpen.setText("Open")
        self.actionOpen.setShortcut("CTRL+O")
        self.actionSave.setText("Save")
        self.actionSave.setShortcut("CTRL+S")
        self.actionPreferences.setText("Preferences")
        self.actionPreferences.setShortcut("CTRL+P")
        self.actionSave_with_name.setText("Save with name")
        self.actionExit.setText("Exit")
        # menuEdit
        self.menuEdit.setTitle("&Edit")
        self.actionNewMedia.setText("Add media")
        self.actionNewMedia.setShortcut("CTRL+M")
        self.actionUndo.setText('Undo')
        self.actionUndo.setShortcut('CTRL+Z')
        self.actionRedo.setText('Redo')
        self.actionRedo.setShortcut('CTRL+Y')
        self.actionSelectAll.setText("Select all")
        self.actionSelectAll.setShortcut("CTRL+A")
        self.actionDeselectAll.setText("Deselect all")
        self.actionDeselectAll.setShortcut("CTRL+SHIFT+A")
        self.actionInvertSelection.setText("Invert selection")
        self.actionInvertSelection.setShortcut("CTRL+I")
        self.actionMultiEdit.setText("Edit selected media")
        self.actionMultiEdit.setShortcut("CTRL+SHIFT+E")
        # menuLayout
        self.menuLayout.setTitle("&Layout")
        # menuTools
        self.menuTools.setTitle("&Tools")
        self.actionMultiEdit.setText("Edit selected media")
        # menuAbout
        self.menuAbout.setTitle("&About")
        self.actionAbout.setText("About")
        self.actionAbout_Qt.setText("About Qt")

    def setProgramLayout(self, layout):
        if(self.collectorUi is not None):
            self.collectorUi.hide()
        self.collectorUi = layout

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        self.collectorUi.setSizePolicy(sizePolicy)
        self.gridLayout.addWidget(self.collectorUi, 0, 0)

        self.collectorUi.show()

    def newProgram(self):
        MainWindow.PREFERENCES_WIDGETS = [general.General]
        self.newProgramAction.emit()

    def openProgram(self):
        MainWindow.PREFERENCES_WIDGETS = [general.General]

        filepath = QtGui.QFileDialog.getOpenFileName(parent=self, filter='*.xml', directory=QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation))
        if(filepath == ''):
            return False
        self.openProgramAction.emit(filepath)
        self.file = filepath
        return True

    def save(self):
        if(self.file == ''):
            self.saveWithName()
        else:
            self.saveProgramAction.emit(self.file)

    def saveWithName(self):
        self.file = QtGui.QFileDialog.getSaveFileName(parent=self, filter='*.xml', directory=QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation))
        if(self.file != ''):
            if(not self.file.endswith('.xml')):
                self.file += '.xml'
            self.save()

    def showPreferences(self):
        prefUi = preferences.Preferences(MainWindow.PREFERENCES_WIDGETS, conf=configuration.toDict(), apply=False)

        def update(conf):
            configuration.updateFromDict(conf)
            configuration.write()

        prefUi.onApply.connect(update)
        prefUi.exec_()

    def closeEvent(self, e):
        self.exit()

    def exit(self):
        exit(0)

    def addMedia(self):
        files = QtGui.QFileDialog.getOpenFileNames(self, "Add media", QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), "Audio files (*.wav *.flac *.mp3 *.ogg);;Any file (*)")
        self.setCursor(QtCore.Qt.WaitCursor)
        self.addMediaAction.emit(files)
        self.setCursor(QtCore.Qt.ArrowCursor)

    def multiEdit(self):
        self.multiEditAction.emit()

    def selectAll(self):
        self.selectAllAction.emit()

    def deselectAll(self):
        self.deselectAllAction.emit()

    def invertSelection(self):
        self.invertSelectionAction.emit()
